//
//  UUCarManager.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 22/01/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUCarManager.h"
#import <UUFoundation/UUIncrementDataManager.h>
#import <UUFoundation/DKDataManager.h>
#import "UUCarRequestModel.h"
#import "UUCarUtility.h"
#import "UUCarAddRequestModel.h"
#import "UUCarEditRequestModel.h"
#import "UUCarDeleteRequestModel.h"

@interface UUCarManager ()

@property (nonatomic, strong) UUIncrementDataManager *carDataManager;

@end

@implementation UUCarManager

- (instancetype)init {
    self = [super init];
    if (self) {
        self.carDataManager = [UUIncrementDataManager managerWithConfiguration:
                               [UUIncrementDataManagerConfiguration configurationWithRequestModelClass:[UUCarRequestModel class]
                                                                                        storeContainer:[UUCarUtility carDefaults]]];
    }
    return self;
}

- (void)asyncUpdateCars {
    WEAK_SELF()
    [self.carDataManager asyncIncrementUpdateWithCompleteBlock:^(BOOL hadUpdate, NSArray<id> *insert, NSArray<id> *delete, NSError *error) {
        if (hadUpdate) {
            if (insert.count > 0) {
                [weakSelf notifyObserversWithSelector:@selector(carManagerDidUpdateCars) withObject:nil];
            }
            
            if (delete.count > 0) {
                [weakSelf notifyObserversWithSelector:@selector(carManagerDidDeleteCars:) withObject:delete];
            }
        }
    }];
}

- (NSArray<NSNumber *> *)fetchCarsForStatus:(UUCarReviewStatus)status {
    return [self fetchCarsForStatus:status greaterThanOrEqualToCarCategory:nil];
}

- (NSArray<NSNumber *> *)fetchCarsForStatus:(UUCarReviewStatus)status greaterThanOrEqualToCarCategory:(NSNumber *)carCategory {
    return [self fetchCarsForStatus:status greaterThanOrEqualToCarCategory:carCategory fleetId:nil];
}

- (NSArray<NSNumber *> *)fetchCarsForStatus:(UUCarReviewStatus)status greaterThanOrEqualToCarCategory:(NSNumber *)carCategory fleetId:(NSNumber *)fleetId {
    NSArray *carCategories = [GetCarCategoryManager() fetchCarCategoriesGreaterThanOrEqualToCarCategory:carCategory];
    NSMutableString *query = [NSMutableString stringWithFormat:@"select carId from UUCarModel "
                              "where "
                              "status = %ld ", status];
    
    if (fleetId != nil) {
        [query appendFormat:@"and fleetId = %@ ", fleetId];
    }
    
    if (carCategory != nil) {
        [query appendFormat:@"and carType in (%@) ", [carCategories componentsJoinedByString:@","]];
    }
    
    [query appendString:@"order by updateTime desc"];
    
    NSMutableArray<NSNumber *> *cars = [NSMutableArray array];
    [[UUCarModel getUsingLKDBHelper] executeDB:^(FMDatabase * _Nonnull db) {
        FMResultSet *set = [db executeQuery:query];
        while ([set next]) {
            NSNumber *carId = @([set intForColumnIndex:0]);
            [cars addObject:carId];
        }
        
        [set close];
    }];
    
    return cars;
}

- (UUCarModel *)fetchCarWithCarId:(id)carId {
    return (UUCarModel *)[self.carDataManager fetchModelWithPrimaryKeyValue:carId];
}

- (void)asyncDeleteCarWithCarId:(NSNumber *)carId completeBlock:(void (^)(NSError *error))completeBlock {
    UUCarDeleteRequestModel *requestModel = [UUCarDeleteRequestModel new];
    requestModel.carId = carId;
    
    WEAK_SELF();
    [[DKDataManager new] requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
        if (error == nil) {
            [weakSelf asyncUpdateCars];
        }
        
        BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, error);
    }];
}

- (void)addCarWithFleetId:(NSNumber *)fleetId
                   carNum:(NSString *)carNum
                  carType:(NSNumber *)carType
                   isSelf:(BOOL)isSelf
           vehicleLicense:(NSString *)vehicleLicense
     vehicleLicenseDeputy:(NSString *)vehicleLicenseDeputy
                insurance:(NSString *)insurance
         transportLicense:(NSString *)transportLicense
            completeBlock:(void (^)(NSError *error))completeBlock {
    UUCarAddRequestModel *requestModel = [UUCarAddRequestModel new];
    requestModel.motorcadeId = fleetId;
    requestModel.carNum = carNum;
    requestModel.carType = carType;
    requestModel.isSelf = isSelf;
    requestModel.vehicleLicense = vehicleLicense;
    requestModel.vehicleLicenseDeputy = vehicleLicenseDeputy;
    requestModel.insurance = insurance;
    requestModel.transportLicense = transportLicense;
    
    WEAK_SELF();
    [[DKDataManager new] requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
        if (error == nil) {
            [weakSelf asyncUpdateCars];
        }
        
        BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, error);
    }];
}

- (void)updateCarWithCarId:(NSNumber *)carId
                   fleetId:(NSNumber *)fleetId
                    carNum:(NSString *)carNum
                   carType:(NSNumber *)carType
                    isSelf:(BOOL)isSelf
            vehicleLicense:(NSString *)vehicleLicense
      vehicleLicenseDeputy:(NSString *)vehicleLicenseDeputy
                 insurance:(NSString *)insurance
          transportLicense:(NSString *)transportLicense
             completeBlock:(void (^)(NSError *error))completeBlock {
    UUCarEditRequestModel *requestModel = [UUCarEditRequestModel new];
    requestModel.carId = carId;
    requestModel.motorcadeId = fleetId;
    requestModel.carNum = carNum;
    requestModel.carType = carType;
    requestModel.isSelf = isSelf;
    requestModel.vehicleLicense = vehicleLicense;
    requestModel.vehicleLicenseDeputy = vehicleLicenseDeputy;
    requestModel.insurance = insurance;
    requestModel.transportLicense = transportLicense;
    
    WEAK_SELF();
    [[DKDataManager new] requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
        if (error == nil) {
            [weakSelf asyncUpdateCars];
        }
        
        BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, error);
    }];
}

@end
